package cjyyp.buffer;

import cjyyp.buffer.util.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@Slf4j
public class 初识Buffer {
    static String filePath = "F:\\LearningMaterials\\netty,nio黑马\\netty\\nio\\src\\main\\resources\\data.txt";

    public static void main(String[] args) throws IOException {
//        //得到channel
//        FileChannel fileChannel = new FileInputStream(filePath).getChannel();
//        //得到缓冲区
//        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
//        //将channel的数据写入缓存区
//        fileChannel.read(byteBuffer);
//        //将缓存区切换至读模式
//        byteBuffer.flip();
//        //遍历 todo 问题：这里只遍历到1234567890，后面内容没有了，怎么解决？
//        while (byteBuffer.hasRemaining()) {
//            log.info("[{}]",(char) byteBuffer.get());
//        }

        //todo 解决：分片读取
        FileChannel fileChannel = new FileInputStream(filePath).getChannel();
        //得到缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        while (fileChannel.read(byteBuffer) != -1) {
            //切换至读模式
            byteBuffer.flip();
            ByteBufferUtil.debugAll(byteBuffer);
            while (byteBuffer.hasRemaining()) {
                log.info("[{}]",(char) byteBuffer.get());
            }
            //切换至写模式
            byteBuffer.clear();
        }
    }
}
